//
//  HttpRequest.m
//  LeaseMC
//
//  Created by fly驰 on 16/8/18.
//  Copyright © 2016年 XFKJ. All rights reserved.
//

#import "HttpRequest.h"
#import "Macros.h"
#import "BaseNavigationController.h"
#import "LoginViewController.h"

static NSString *s_baseUrl;
//#define  BASEURL   @"http://192.168.1.9:8099"
#define  BASEURL     @"http://www.hotidayo.com"

@implementation HttpRequest
#pragma mark - Life cycle
- (void)dealloc {
    _urlString=nil;
    _parameters=nil;
}

+ (instancetype)request{
    return [[self alloc] init];
}

+ (void)setBaseUrl:(NSString*)baseUrl{
    s_baseUrl = baseUrl;
}

+ (NSString *)getBaseUrl{
    return s_baseUrl;
}

- (instancetype)init {
    self = [super init];
    if(self) {
        _parameters = [[NSMutableDictionary alloc] init];
        _imgArr = [[NSArray alloc] init];
    }
    return (self);
}

-(void)preLogin{
    //不是登录接口
    if (![_urlString isEqualToString:@"login"]){
        NSHTTPCookie *cookie = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey:@"lgfcookie"]];
        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        //        LGFLog(@"不是调登录接口 - 设置进去的cookie %@--",cookie);
        [cookieStorage setCookie:cookie];
    }
    
    if ([_urlString isEqualToString:@"login"]){
        NSArray *cookiesArray = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        for (NSHTTPCookie *cookie in cookiesArray) {
            //            LGFLog(@"登录接口 - 清除cookie %@--",cookie);
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
        }
    }
}

//-(void)successLoginSaveCookieWithUrl:(NSString*)urlStr task:(NSURLSessionDataTask*)task{
//    if ([_urlString  isEqualToString:@"login"]) {
//        LGFLog(@"---调登录接口01---");
//        NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
//        LGFLog(@"调登录接口fields = %@",fields);
//        //获取cookie方法1
//        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:[NSURL URLWithString:urlStr]];
//        for (NSHTTPCookie *cookie in cookies) {
//            LGFLog(@"调登录接口cookie = %@",cookie);
//            if ([cookie.name isEqualToString:@"JSESSIONID"]) {
//                LGFLog(@"---调登录接口02---");
//                NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//                //        LGFLog(@"不是调登录接口 - 设置进去的cookie %@--",cookie);
//                [cookieStorage setCookie:cookie];
//                NSData * data  = [NSKeyedArchiver archivedDataWithRootObject:cookie];
//                [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"lgfcookie"];
//                [[NSUserDefaults standardUserDefaults] synchronize];
//            }
//        }
//    }
//}

#pragma mark - POST请求
- (void) postWithManager:(id)requestOperationManager
                 success:(HttpRequestSuccess)success
                 failure:(HttpRequestFailed)failure{
    //Https
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
    securityPolicy.allowInvalidCertificates = YES;
    //请求
    if (requestOperationManager ==nil ) {
        requestOperationManager = [HttpRequest requestOperationManager];
    }
    [self preLogin];//登录前设置一个cookie
    WEAKSELF
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@", BASEURL, _urlString];
    LGFLog(@"参数 - %@ url = %@",_parameters,urlStr);
    [requestOperationManager POST:urlStr  parameters:_parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        LGFLog(@"0000000responseObject = %@",responseObject);
        //NSLog(@"\n======================================\n");
        //NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
        //[weakSelf successLoginSaveCookieWithUrl:urlStr task:task];
        if ([_urlString  isEqualToString:@"login"]) {
            //LGFLog(@"---调登录接口01---");
            NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
            //LGFLog(@"调登录接口fields = %@",fields);
            //获取cookie方法1
            NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:[NSURL URLWithString:urlStr]];
            for (NSHTTPCookie *cookie in cookies) {
                // LGFLog(@"调登录接口cookie = %@",cookie);
                if ([cookie.name isEqualToString:@"JSESSIONID"]) {
                    //LGFLog(@"---调登录接口02---");
                    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                    LGFLog(@"不是调登录接口 - 设置进去的cookie %@--",cookie);
                    [cookieStorage setCookie:cookie];
                    NSData * data  = [NSKeyedArchiver archivedDataWithRootObject:cookie];
                    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"lgfcookie"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
        }
        if (success!=nil) {//成功
            //用户过期或session失效
            if ([responseObject[@"status"] intValue] == 1205 ||[responseObject[@"status"] intValue] == 1404) {
                //                LGFLog(@"用户过期%@",responseObject);
                [SOAutoHideMessageView showMessage:[responseObject safeJsonObjectForKey:@"msg"] inView:nil hideDelay:1];
                BaseNavigationController * Nav = [[BaseNavigationController alloc] initWithRootViewController:[LoginViewController new]];
                kAppWindow.rootViewController = Nav;
                return ;
            }
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure!=nil) {//失败
            failure(error);
        }
    }];
}

#pragma mark - GET请求
- (void)getWithManager:(id)requestOperationManager
               success:(HttpRequestSuccess)success
               failure:(HttpRequestFailed)failure{
    //Https
    /*
     AFSSLPinningModeNone
     不做任何验证，只要服务器返回了证书就通过
     AFSSLPinningModePublicKey
     只验证公钥部分，只要公钥部分一致就验证通过
     AFSSLPinningModeCertificate
     除了公钥外，其他能容也要一致才能通过验证。
     */
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    //请求
    if (requestOperationManager ==nil ) {
        requestOperationManager = [HttpRequest requestOperationManager];
    }
    WEAKSELF
    [requestOperationManager GET:[NSString stringWithFormat:@"%@%@", BASEURL, _urlString] parameters:_parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //成功
        if (success!=nil) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        if (failure!=nil) {
            failure(error);
        }
    }];
}

#pragma mark - 上传图片文件
- (void)upLoadPicturesWithManager:(id)requestOperationManager
                          success:(HttpUploadSuccess)success
                          failure:(HttpRequestFailed)failure{
    //Https
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
    securityPolicy.allowInvalidCertificates = YES;
    //请求
    if (requestOperationManager ==nil ) {
        requestOperationManager = [HttpRequest requestOperationManager];
    }
    [self preLogin];//登录前设置一个cookie
    LGFLog(@"上传图片文件参数 = %@ url = %@",_parameters,[NSString stringWithFormat:@"%@/%@", BASEURL, _urlString]);
    //    WEAKSELF
    [requestOperationManager POST:[NSString stringWithFormat:@"%@/%@", BASEURL, _urlString] parameters:_parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        LGFLog(@"--%zd",[_imgArr count]);
        for (NSInteger idx = 0; idx < [_imgArr count]; idx ++){
            //            LGFLog(@"上传图片文件参数 = %@",_imgArr[0]);
            NSData *imageData;
            imageData = UIImageJPEGRepresentation([_imgArr[idx] valueForKey:@"img"], 0.5);
            [formData appendPartWithFileData:imageData name:[_imgArr[idx] valueForKey:@"name"] fileName:[_imgArr[idx] valueForKey:@"filename"] mimeType:@"image/jpg/png/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功
        if (success!=nil) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        if (failure!=nil) {
            failure(error);
        }
    }];
}

+ (id)requestOperationManager{
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",@"text/javascript",nil];
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 30.f;
    return manager;
}

@end
